import { getProfile, updateUserInfo, updateUserPhoto } from '@/api/user.js'

export default {
  namespaced: true,
  state: {
    userInfo: {}
  },
  mutations: {
    mSetUserInfo (state, newUserInfo) {
      state.userInfo = newUserInfo
    },
    mUpdateUserName (state, newName) {
      state.userInfo.name = newName
    },
    mUpdateUserPhoto (state, newPhoto) {
      state.userInfo.photo = newPhoto
    },
    // 修改生日
    mUpdateUserBirthday (state, newBirthday) {
      state.userInfo.birthday = newBirthday
    },
    mUpdateGender (state, newGender) {
      state.userInfo.gender = newGender
    }
  },
  actions: {
    async getProfile (context) {
      try {
        // console.log('modules,getProfile')
        const { data: { data } } = await getProfile()
        // console.log(data)
        context.commit('mSetUserInfo', data)
      } catch (err) {
        throw new Error(err)
      }
    },
    // 修改用户名
    async updateUserName (context, newName) {
      try {
        await updateUserInfo({
          name: newName
        })
        context.commit('mUpdateUserName', newName)
      } catch (err) {
        // console.log(err)
        throw new Error(err)
      }
    },
    // 修改头像
    async updateUserPhoto (context, file) {
      try {
        const { data: { data } } = await updateUserPhoto(file)
        context.commit('mUpdateUserPhoto', data.photo)
      } catch (err) {
        // console.log(err)
        throw new Error(err)
      }
    }
  }
}
